//
//  AddressListVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/30.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD
import MJRefresh

class M_MyAddressListVC: BaseViewControllerWithHeader,UITableViewDataSource,UITableViewDelegate {
    //定义一个闭包类型
    typealias saveBlock = ([String : Any?]) -> Void
    var saveBtnBack: saveBlock?
    func callSaveBlock(block: @escaping saveBlock) {
        saveBtnBack = block
    }
    
    var zoneCode = "105002"
    var userListAry = [[String : Any?]]()
    var extListAry = [[String : Any?]]()
    var tableView = UITableView(frame: CGRect.zero, style: .grouped)
    let tabhead = M_AddressHeadView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
        refreshall()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    
    func getUserList(isDefault: Bool=false) {
        MBProgressHUD.showOrIncrease()
        var params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
        if isDefault {
            params.updateValue(isDefault, forKey: "isDefault")
        }
        API.request(url: .M_GetUserContactAddressList, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                self.userListAry = []
                if let dl = result.data?.getDictionary("data")?.getDictList("contactAddress") {
                    for item in dl {
                        self.userListAry.append(item)
                    }
                }
                self.tableView.reloadData()
            }
        }
    }
    
    
    func getExtList() {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "sort":"119001",
                                    "dir":"106001",
                                    "pageIndex":1,
                                    "pageSize":1000]
        API.request(url: .M_SelfAddress, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                self.extListAry = []
                if let dl = result.data?.getDictionary("data")?.getDictList("selfAddress") {
                    for item in dl {
                        self.extListAry.append(item)
                    }
                }
                self.tableView.reloadData()
            }
        }
    }
}


// MARK: UI
extension M_MyAddressListVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white

        //画横线
        let line = headView.drawView { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
//        headTitle.text = "选择地址"
        
        //画横线
//        let line = headView.drawView { (make) in
//            make.left.right.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-1)
//            make.height.equalTo(2)
//        }
//        line.backgroundColor = .xF2F2F2
        
        //添加列表
        let _ = getRefreshHeader()
        tableView.backgroundColor = UIColor.clear;
        safeView.addSubview(tableView)
        tableView.register(M_AddressCell.self, forCellReuseIdentifier: "M_AddressCell")
        tableView.register(M_AddressExtractfCell.self, forCellReuseIdentifier: "M_AddressExtractfCell")
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 72
        tableView.rowHeight = UITableView.automaticDimension
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom).offset(10)
            make.left.right.bottom.equalToSuperview()
        }
        
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        drawRightButton(imageName: "xiangqingkefu_82")
        .addTarget(self, action: #selector(_kefuButtonClick(button:)), for: .touchUpInside)
    }

        func getRefreshHeader()->MJRefreshHeader {
    //        顶部的下拉初始化
            let header = MJRefreshNormalHeader()
            header.lastUpdatedTimeLabel.isHidden = true
            tableView.mj_header = header
            header.setTitle("下拉刷新...", for: .idle)
            header.setTitle("下拉刷新...", for: .pulling)
            header.setTitle("下拉更新中...", for: .refreshing)
            header.setTitle("完成...", for: .willRefresh)
            header.setTitle("下拉刷新...", for: .noMoreData)
            header.setRefreshingTarget(self, refreshingAction: #selector(onHeaderRequery))

    //        顶部的处理逻辑：
            return tableView.mj_header!
        }
}

// MARK: event & action
extension M_MyAddressListVC {
    func refreshall() {
            getUserList()
    }
    
    @objc func _saveButtonClick(button: Button) {
        var curdic = [String:Any?]()
        if let indexpath = tableView.indexPathForSelectedRow {
            curdic.updateValue("103002", forKey: "orderDeliverModeCode")
            curdic.updateValue(anyToString(userListAry[indexpath.row].getInt("contactID")), forKey: "orderDeliverSiteCode")
            var ad = userListAry[indexpath.row].getString("receiptName") ?? ""
            ad += "     "
            ad += userListAry[indexpath.row].getString("mobile") ?? ""
            ad += "\n\r"
            ad += userListAry[indexpath.row].getString("provinceName") ?? ""
            ad += userListAry[indexpath.row].getString("cityName") ?? ""
            ad += userListAry[indexpath.row].getString("districtName") ?? ""
            ad += userListAry[indexpath.row].getString("townName") ?? ""
            ad += userListAry[indexpath.row].getString("detailAddress") ?? ""
            curdic.updateValue(ad, forKey: "name")
            curdic.updateValue(userListAry[indexpath.row].getString("receiptName"), forKey: "receiptName")
            curdic.updateValue(userListAry[indexpath.row].getString("mobile"), forKey: "mobile")
        }
        else {
            let popup = PopupSureBox(title: "请选择地址", sureText: "确定")
            popup.show(vc: UIViewController.topMostController() ?? self)
            popup.onSureButtonClick = {
                //确定执行
            }
            return
        }
        if saveBtnBack != nil {
            saveBtnBack!(curdic)
            popViewController()
        }
    }
    
    @objc func _addButtonClick(button: Button) {
        let vc = M_AddressDetailVC()
        vc.isadd = true
        pushViewController(vc)
        vc.callSucceedBack(block: { (v) in
            self.getUserList()
        })
    }
    
    @objc func _kefuButtonClick(button: Button) {
        let vc = M_SimpleArticleVC()
        pushViewController(vc)
        let qidiandic = LocalStorage.getDic(forKey: QIDIAN_KEY)
        vc.loadUrl(qidiandic?.getString("id") ?? "https://url.cn/50hfdES?_type=wpa&qidian=true")

        vc.headTitle.text = "联系客服"
    }
    
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func onHeaderRequery() {
        //        顶部数据重新加载
        tableView.mj_header.endRefreshing()
        tableView.reloadData()
    }
    

        ///MARK: UITableViewDelegate
        // 选中cell后执行此方法
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print(indexPath.row)
            _saveButtonClick(button: Button())
        }
        
        ///MARK: UITableViewDataSource
        func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//            if zoneCode == "105002" {
//                tabhead.extAddressBtn.isHidden = true
//            }
//            else if zoneCode == "105001" {
//                tabhead.extAddressBtn.isHidden = false
//            }
//            return tabhead
            return nil
        }
        
        //头部高度
        func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
           return 0
        }
        
        //组数
        func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }
        
        //尾部高度
        func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
            if userListAry.count > 0 {
                return 80
            }
            else {
                return tableView.bounds.height - 78
            }
            
        }
    
    //尾部view
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footView = UIView()
        if userListAry.count > 0 {
            let btn = footView.drawButton(title: "新建收货地址", titleColor: .white, fontSize: 15) { (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-20)
                make.left.equalToSuperview().offset(30)
                make.right.equalToSuperview().offset(-30)
                make.height.equalTo(35)
            }
            btn.backgroundColor = .xFC4C02
            btn.layer.cornerRadius = 7
            btn.clipsToBounds = true
            btn.addTarget(self, action: #selector(_addButtonClick(button:)), for: .touchUpInside)
            return footView
        }
        else {
            footView.drawImage(named: "dizhi673") { (make) in
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview().offset(-40)
            }
            footView.drawLabel(text: "目前没有收货信息", fontSize: 18, textColor: .x333333) { (make) in
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview().offset(5)
            }
            
            let btn = footView.drawButton(title: "新建收货地址", titleColor: .white, fontSize: 15) { (make) in
                make.centerX.equalToSuperview()
                make.bottom.equalToSuperview().offset(-20)
                make.left.equalToSuperview().offset(30)
                make.right.equalToSuperview().offset(-30)
                make.height.equalTo(35)
            }
            btn.backgroundColor = .xFC4C02
            btn.layer.cornerRadius = 7
            btn.clipsToBounds = true
            btn.addTarget(self, action: #selector(_addButtonClick(button:)), for: .touchUpInside)
            return footView
        }
    }
        // cell的个数
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return userListAry.count
        }
    
        // UITableViewCell
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cellid = "M_AddressCell"
            var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? M_AddressCell
            if cell==nil {
                cell = M_AddressCell(style: .subtitle, reuseIdentifier: cellid)
            }
            
            cell?.celldata = userListAry[indexPath.row]
            cell?.calleditBlock(block: { (data) in
                let vc = M_AddressDetailVC()
                vc.contactID = data.getInt("contactID") ?? -1
                vc.provinceCode = data.getString("provinceCode") ?? ""
                vc.cityCode = data.getString("cityCode") ?? ""
                vc.districtCode = data.getString("districtCode") ?? ""
                vc.townCode = data.getString("townCode") ?? ""
                var ad = data.getString("provinceName") ?? ""
                ad += " "
                ad += data.getString("cityName") ?? ""
                ad += " "
                ad += data.getString("districtName") ?? ""
                ad += " "
                ad += data.getString("townName") ?? ""
                vc.adCode.text = ad
                vc.receiptName.text = data.getString("receiptName") ?? ""
                vc.mobile.text = data.getString("mobile") ?? ""
                vc.detailAddress.text = data.getString("detailAddress") ?? ""
                vc.postCode.text = data.getString("postcode") ?? ""
                vc.isDefault.isOn = data.getBool("isDefault") ?? false
                self.pushViewController(vc)
                vc.callSucceedBack(block: { (v) in
                    self.getUserList()
                })
            })
            return cell!
            
        }
}
